<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>订单导航</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .map-container {
            height: 100vh;
            position: relative;
        }
        #baiduMap {
            width: 100%;
            height: 100%;
        }
        .order-list {
            position: absolute;
            top: 20px;
            left: 20px;
            width: 300px;
            max-height: calc(100vh - 40px);
            background: white;
            border-radius: 15px;
            padding: 1rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow-y: auto;
            z-index: 1000;
        }
        .order-item {
            padding: 1rem;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .order-item:hover {
            background-color: #f8f9fa;
        }
        .order-item:last-child {
            border-bottom: none;
        }
        .order-status {
            padding: 0.25rem 0.5rem;
            border-radius: 10px;
            font-size: 0.8rem;
        }
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        .status-processing {
            background-color: #d1e7dd;
            color: #0f5132;
        }
        .order-info {
            color: #6c757d;
            font-size: 0.9rem;
        }
        .nearby-stations {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin: 15px;
            overflow: hidden;
        }
        .station-list-header {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .refresh-btn {
            padding: 4px 8px;
            font-size: 0.9rem;
        }
        .station-list {
            max-height: calc(100vh - 200px);
            overflow-y: auto;
        }
        .station-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            transition: background-color 0.2s;
        }
        .station-item:hover {
            background-color: #f8f9fa;
        }
        .station-item:last-child {
            border-bottom: none;
        }
        .station-info {
            margin-bottom: 10px;
        }
        .station-name {
            font-size: 1.1rem;
            font-weight: 500;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .station-status {
            font-size: 0.8rem;
            padding: 2px 8px;
            border-radius: 12px;
            margin-left: auto;
        }
        .status-open {
            color: #198754;
            background-color: #d1e7dd;
        }
        .status-closed {
            color: #dc3545;
            background-color: #f8d7da;
        }
        .station-address {
            color: #666;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .station-details {
            display: flex;
            gap: 20px;
            color: #666;
            font-size: 0.9rem;
            margin-bottom: 8px;
        }
        .detail-item {
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .station-distance {
            color: #0d6efd;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .station-actions {
            display: flex;
            gap: 10px;
        }
        .station-actions .btn {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
        /* 自定义滚动条样式 */
        .station-list::-webkit-scrollbar {
            width: 6px;
        }
        .station-list::-webkit-scrollbar-track {
            background: #f1f1f1;
        }
        .station-list::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 3px;
        }
        .station-list::-webkit-scrollbar-thumb:hover {
            background: #555;
        }
    </style>
</head>
<body>
    <div class="map-container">
        <!-- 订单列表 -->
        <div class="order-list">
            <h5 class="mb-3">待处理订单</h5>
            <div id="orderList">
                <div class="order-item" th:each="order : ${orders}" 
                     th:onclick="'showOrderRoute(' + ${order.id} + ')'">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div>
                            <span class="fw-bold" th:text="${'订单 #' + order.id}">订单 #123</span>
                        </div>
                        <span class="order-status" 
                              th:classappend="${order.status == 1 ? 'status-pending' : 'status-processing'}"
                              th:text="${order.status == 1 ? '待处理' : '处理中'}">待处理</span>
                    </div>
                    <div class="order-info">
                        <div class="mb-1">
                            <i class="fas fa-map-marker-alt me-2"></i>
                            <span th:text="${order.address}">回收地址</span>
                        </div>
                        <div class="mb-1">
                            <i class="fas fa-user me-2"></i>
                            <span th:text="${order.contactName}">联系人</span>
                        </div>
                        <div>
                            <i class="fas fa-phone me-2"></i>
                            <span th:text="${order.contactPhone}">联系电话</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 百度地图 -->
        <div id="baiduMap"></div>

        <!-- 附近回收站列表 -->
        <div class="nearby-stations">
            <div class="station-list-header">
                <h5 class="mb-0">附近回收站</h5>
                <button class="btn btn-sm btn-outline-primary refresh-btn" onclick="refreshStations()">
                    <i class="fas fa-sync-alt"></i> 刷新
                </button>
            </div>
            <div class="station-list" id="stationList">
                <div class="station-item" th:each="station : ${stations}">
                    <div class="station-info">
                        <div class="station-name">
                            <i class="fas fa-recycle"></i>
                            <span th:text="${station.name}">回收站名称</span>
                            <span class="station-status" th:classappend="${station.status == 1 ? 'status-open' : 'status-closed'}">
                                <i class="fas fa-circle"></i>
                                <span th:text="${station.status == 1 ? '营业中' : '已关闭'}"></span>
                            </span>
                        </div>
                        <div class="station-address">
                            <i class="fas fa-map-marker-alt"></i>
                            <span th:text="${station.address}">回收站地址</span>
                        </div>
                        <div class="station-details">
                            <div class="detail-item">
                                <i class="fas fa-phone"></i>
                                <span th:text="${station.contactPhone}">联系电话</span>
                            </div>
                            <div class="detail-item">
                                <i class="fas fa-clock"></i>
                                <span th:text="${station.businessHours}">营业时间</span>
                            </div>
                        </div>
                        <div class="station-distance">
                            <i class="fas fa-walking"></i>
                            <span class="distance-value">计算中...</span>
                        </div>
                    </div>
                    <div class="station-actions">
                        <button class="btn btn-sm btn-primary" th:onclick="'showRoute(\'' + ${station.latitude} + ',' + ${station.longitude} + '\')'">
                            <i class="fas fa-route"></i> 查看路线
                        </button>
                        <a th:href="'tel:' + ${station.contactPhone}" class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-phone"></i> 联系
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=mNFuffn83uuKvzWesj3uqfVho6CVP9LI"></script>
    <script th:src="@{/js/map-component.js}"></script>
    <script th:inline="javascript">
        let mapComponent;
        const orders = /*[[${orders}]]*/ [];
        let currentRoute = null;
        
        document.addEventListener('DOMContentLoaded', async () => {
            try {
                mapComponent = new BaiduMapComponent('baiduMap', {
                    enableGeolocation: true,
                    onMapInitialized: function(map) {
                        // 添加所有订单标记
                        orders.forEach(order => {
                            const content = `
                                <div class="p-3">
                                    <h5>订单 #${order.id}</h5>
                                    <p><i class="fas fa-map-marker-alt me-2"></i>${order.address}</p>
                                    <p><i class="fas fa-user me-2"></i>${order.contactName}</p>
                                    <p><i class="fas fa-phone me-2"></i>${order.contactPhone}</p>
                                    <button class="btn btn-primary btn-sm" onclick="startNavigation(${order.latitude}, ${order.longitude})">
                                        开始导航
                                    </button>
                                </div>
                            `;
                            
                            mapComponent.addMarker(`order-${order.id}`, 
                                new BMap.Point(order.longitude, order.latitude),
                                {
                                    infoWindow: {
                                        content: content,
                                        title: `订单 #${order.id}`
                                    }
                                }
                            );
                        });
                    }
                });
                
                await mapComponent.init();
            } catch (error) {
                console.error('地图初始化失败:', error);
            }
        });

        // 显示订单路线
        function showOrderRoute(orderId) {
            const order = orders.find(o => o.id === orderId);
            if (order) {
                // 清除之前的路线
                if (currentRoute) {
                    mapComponent.clearRoute();
                }
                
                // 获取当前位置并规划路线
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(
                        (position) => {
                            const start = [position.coords.longitude, position.coords.latitude];
                            const end = [order.longitude, order.latitude];
                            mapComponent.addRoute(start, end);
                            currentRoute = orderId;
                            
                            // 打开信息窗口
                            const marker = mapComponent.markers.get(`order-${orderId}`);
                            const infoWindow = mapComponent.infoWindows.get(`order-${orderId}`);
                            if (marker && infoWindow) {
                                mapComponent.map.openInfoWindow(infoWindow, marker.getPosition());
                            }
                        },
                        (error) => {
                            console.error('获取位置失败:', error);
                            alert('无法获取您的位置，请检查位置权限设置');
                        }
                    );
                } else {
                    alert('您的浏览器不支持地理定位');
                }
            }
        }

        // 开始导航
        function startNavigation(targetLat, targetLng) {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    (position) => {
                        const start = [position.coords.longitude, position.coords.latitude];
                        const end = [targetLng, targetLat];
                        mapComponent.addRoute(start, end);
                    },
                    (error) => {
                        console.error('获取位置失败:', error);
                        alert('无法获取您的位置，请检查位置权限设置');
                    }
                );
            } else {
                alert('您的浏览器不支持地理定位');
            }
        }

        // 获取当前位置并计算距离
        function getCurrentLocationAndCalculateDistances() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    (position) => {
                        const currentLat = position.coords.latitude;
                        const currentLng = position.coords.longitude;
                        
                        document.querySelectorAll('.station-item').forEach(item => {
                            const stationLat = parseFloat(item.getAttribute('data-lat'));
                            const stationLng = parseFloat(item.getAttribute('data-lng'));
                            const distance = calculateDistance(currentLat, currentLng, stationLat, stationLng);
                            
                            const distanceElement = item.querySelector('.distance-value');
                            if (distance < 1) {
                                distanceElement.textContent = `${Math.round(distance * 1000)}米`;
                            } else {
                                distanceElement.textContent = `${distance.toFixed(1)}公里`;
                            }
                        });
                    },
                    (error) => {
                        console.error('获取位置失败:', error);
                        document.querySelectorAll('.distance-value').forEach(el => {
                            el.textContent = '无法获取距离';
                        });
                    }
                );
            }
        }

        // 计算两点之间的距离（公里）
        function calculateDistance(lat1, lng1, lat2, lng2) {
            const R = 6371; // 地球半径（公里）
            const dLat = (lat2 - lat1) * Math.PI / 180;
            const dLng = (lng2 - lng1) * Math.PI / 180;
            const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                      Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                      Math.sin(dLng/2) * Math.sin(dLng/2);
            const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
            return R * c;
        }

        // 刷新回收站列表
        function refreshStations() {
            // 这里可以添加刷新逻辑
            getCurrentLocationAndCalculateDistances();
        }

        // 页面加载完成后计算距离
        document.addEventListener('DOMContentLoaded', () => {
            getCurrentLocationAndCalculateDistances();
        });
    </script>
</body>
</html> 